package com.zjw.socket.demo.starter.messageService;

import java.util.ArrayDeque;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MessageCacheFactory {
  private static final int DEFAULT_CACHE_SIZE = 128;
  private static final Queue<Message> CACHE_QUEUE = new ArrayDeque<>(DEFAULT_CACHE_SIZE);

  private static final Lock CACHE_LOCK = new ReentrantLock(false);

  public static void recycle(Message message) {
    try {
      reset(message);
      CACHE_LOCK.lock();
      if (CACHE_QUEUE.size() < DEFAULT_CACHE_SIZE) {
        CACHE_QUEUE.offer(message);
      }
    } finally {
      CACHE_LOCK.unlock();
    }
  }

  public static Message obtainResponseMessage(Message requestMessage) {
    Message message = obtain();
    message.setToId(requestMessage.getFromId());
    message.setTime(new Date().getTime());
    message.setFromId(0L);
    message.setMessageId(requestMessage.getMessageId());
    return message;
  }

  public static Message obtain() {
    try {
      CACHE_LOCK.lock();
      if (!CACHE_QUEUE.isEmpty()) {
        return CACHE_QUEUE.poll();
      } else {
        return new Message();
      }
    } finally {
      CACHE_LOCK.unlock();
    }
  }

  private static void reset(Message message) {
    message.setTime(0);
    message.setFromId(0);
    message.setTime(0);
    message.setChanel(null);
    message.setProcessStrategy(0);
    message.setType(0);
    message.setBytes(null);
  }
}
